var mysql = require('mysql');

var pool = mysql.createPool({
    // connectionLimit: 10,
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'node_mysql_demo'
});

// 该事件 当池中创建新的连接槽时 触发
pool.on('connection', function (connection) {
    console.log('Connection %d connection', connection.threadId);
});

// 该事件 当从池中获取连接槽时 触发
pool.on('acquire', function (connection) {
    console.log('Connection %d acquired', connection.threadId);
});

// 该事件 当把连接槽放入池中时 触发
pool.on('release', function (connection) {
    console.log('Connection %d released', connection.threadId);
});

// 该事件 当池中连接槽不够用 等待可用连接槽时 触发
pool.on('enqueue', function () {
    console.log('Waiting for available connection slot');
});


module.exports.insertStudent = function (student, cb) {
    pool.query('INSERT t_student VALUES(null, ?, ?, NOW(), NOW())', [student.name, student.sex], function (error, results, fields) {
        if (error) throw error;
        cb(results);
    });
};

module.exports.deleteStudentById = function (id, cb) {
    pool.query('DELETE t_student WHERER id = ?', [id], function (error, results, fields) {
        if (error) throw error;
        cb(results);
    });
};

module.exports.updateStudent = function (student, cb) {
    pool.query(
        'UPDATE t_student SET name = ?, sex = ? WHERER id = ?',
        [student.name, student.sex, student.id],
        function (error, results, fields) {
            if (error) throw error;
            cb(results);
        }
    );
};

module.exports.getStudents = function (cb) {
    pool.query('SELECT * FROM t_student', function (error, results, fields) {
        if (error) throw error;
        cb(results);
    });
};